/*
 * @lc app=leetcode.cn id=1302 lang=typescript
 *
 * [1302] 层数最深叶子节点的和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function deepestLeavesSum(root: TreeNode | null): number {
  let maxDepth = 0;
  let ans = 0;
  const dfs = (node: TreeNode | null, depth: number): number => {
    if (node === null) return 0;
    if (depth === maxDepth) {
      ans += node.val;
    } else if (depth > maxDepth) {
      maxDepth = depth;
      ans = node.val;
    }
    dfs(node.left, depth + 1);
    dfs(node.right, depth + 1);
  };

  dfs(root, 0);
  return ans;
}
// @lc code=end
